<script setup lang="ts">
import {
  getAllInstitution,
  addInstitution,
  updateInstitution,
  delInstitution
} from "@/api/index";
import { ref, onMounted, reactive } from "vue";
import type { TreeNode } from "@/types/common";
import {
  ElTable,
  ElTableColumn,
  ElTag,
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElCard,
  ElSelect,
  ElOption
} from "element-plus";

interface InstitutionData {
  id: number;
  oid: string;
  zh_name: string;
  pid: string;
  class_id: number;
  class_name: string;
  seqnum_id: number | null;
  is_valid: number;
}

interface AddInstitutionForm {
  oid: string;
  pid: string;
  zh_name: string;
  class_id: number;
  class_name: string;
}

interface UpdateInstitutionForm {
  id: number;
  oid: string;
  zh_name: string;
  pid: string;
  class_id: number;
  class_name: string;
  seqnum_id: number | null;
  is_valid: number;
}

// 机构类型枚举
const InstitutionType = {
  SCHOOL: { id: 1, name: "学校" },
  ORGANIZATION: { id: 2, name: "机构" },
  ENTERPRISE: { id: 3, name: "企业" },
  OFFICE: { id: 4, name: "科室" },
  DIVISION: { id: 5, name: "学部" },
  DEPARTMENT: { id: 6, name: "部门" }
} as const;

// 所有可选的机构类型列表
const allInstitutionTypes = [
  {
    id: InstitutionType.ORGANIZATION.id,
    name: InstitutionType.ORGANIZATION.name
  },
  { id: InstitutionType.ENTERPRISE.id, name: InstitutionType.ENTERPRISE.name },
  { id: InstitutionType.OFFICE.id, name: InstitutionType.OFFICE.name },
  { id: InstitutionType.DIVISION.id, name: InstitutionType.DIVISION.name },
  { id: InstitutionType.DEPARTMENT.id, name: InstitutionType.DEPARTMENT.name }
];

const tableData = ref<TreeNode[]>([]);
const expandRowKeys = ref<string[]>([]);
const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const formData = reactive({
  oid: "",
  pid: "",
  zh_name: "",
  class_id: 0,
  class_name: ""
});
const editFormData = reactive<UpdateInstitutionForm>({
  id: 0,
  oid: "",
  zh_name: "",
  pid: "",
  class_id: 0,
  class_name: "",
  seqnum_id: null,
  is_valid: 1
});
const currentRow = ref<TreeNode | null>(null);

// 当前可选的子机构类型列表
const availableChildTypes = ref<Array<{ id: number; name: string }>>([]);

// 将扁平数据转换为树形结构
const convertToTreeData = (data: InstitutionData[]): TreeNode[] => {
  const map = new Map();
  const result: TreeNode[] = [];

  // 先按照class_id和pid排序，确保正确的层级顺序
  const sortedData = [...data].sort((a, b) => {
    // 首先按照pid排序，确保父节点在前
    if (a.pid !== b.pid) {
      return a.pid.localeCompare(b.pid);
    }
    // 然后按照class_id排序
    return a.class_id - b.class_id;
  });

  // 先创建一个以oid为键的映射
  sortedData.forEach(item => {
    map.set(item.oid, {
      id: item.id,
      label: item.zh_name,
      children: [],
      ...item
    });
  });

  // 构建树形结构
  sortedData.forEach(item => {
    const node = map.get(item.oid);
    if (item.pid === "-1") {
      // 根节点（学校）
      result.push(node);
      expandRowKeys.value.push(String(node.id));
    } else {
      // 子节点
      const parent = map.get(item.pid);
      if (parent) {
        // 确保children数组存在
        if (!parent.children) {
          parent.children = [];
        }

        parent.children.push(node);
        // 默认展开第二级（机构和学部）
        if (parent.class_id === InstitutionType.SCHOOL.id) {
          expandRowKeys.value.push(String(node.id));
        }
      }
    }
  });

  return result;
};

// 获取机构数据
const loadInstitutionData = async () => {
  try {
    const response = await getAllInstitution();
    if (response.status === "success" && response.data) {
      tableData.value = convertToTreeData(response.data);
    }
  } catch (error) {
    console.error("获取机构数据失败:", error);
  }
};

// 处理修改按钮点击
const handleEdit = (row: TreeNode) => {
  // 填充表单数据
  editFormData.id = row.id;
  editFormData.oid = row.oid;
  editFormData.zh_name = row.zh_name;
  editFormData.pid = row.pid;
  editFormData.class_id = row.class_id;
  editFormData.class_name = row.class_name;
  editFormData.seqnum_id = row.seqnum_id;
  editFormData.is_valid = row.is_valid;
  editDialogVisible.value = true;
};

// 处理删除按钮点击
const handleDelete = (row: TreeNode) => {
  ElMessageBox.confirm(`确认删除机构"${row.zh_name}"吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const response = await delInstitution(row.id);
        if (response.status === "success") {
          ElMessage.success("删除成功");
          // 重新加载数据
          await loadInstitutionData();
        } else {
          ElMessage.error(response.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除机构失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 用户取消删除操作
    });
};

// 处理新增下一级按钮点击
const handleAddChild = (row: TreeNode) => {
  currentRow.value = row;
  // 预填充表单数据，但允许编辑
  formData.oid = "";
  formData.pid = row.oid; // 默认填充当前节点的oid作为父id
  formData.zh_name = "";
  formData.class_id = 0;
  formData.class_name = "";

  // 设置可选的机构类型为所有类型（除了学校）
  availableChildTypes.value = allInstitutionTypes;

  dialogVisible.value = true;
};

// 处理类型选择变化
const handleTypeChange = (typeId: number) => {
  const selectedType = availableChildTypes.value.find(
    type => type.id === typeId
  );
  if (selectedType) {
    formData.class_id = selectedType.id;
    formData.class_name = selectedType.name;
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    if (!formData.zh_name.trim()) {
      ElMessage.warning("机构名称不能为空");
      return;
    }
    if (!formData.oid.trim()) {
      ElMessage.warning("机构ID不能为空");
      return;
    }
    if (!formData.pid.trim()) {
      ElMessage.warning("父级ID不能为空");
      return;
    }
    if (!formData.class_name.trim()) {
      ElMessage.warning("类型名称不能为空");
      return;
    }

    const response = await addInstitution(formData);
    if (response.status === "success") {
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      // 重新加载数据
      await loadInstitutionData();
      // 展开父节点
      if (
        currentRow.value &&
        !expandRowKeys.value.includes(String(currentRow.value.id))
      ) {
        expandRowKeys.value.push(String(currentRow.value.id));
      }
    } else {
      ElMessage.error("添加失败");
    }
  } catch (error) {
    console.error("添加子机构失败:", error);
    ElMessage.error("添加失败");
  }
};

// 提交修改表单
const handleEditSubmit = async () => {
  try {
    // 表单验证
    if (!editFormData.zh_name.trim()) {
      ElMessage.warning("机构名称不能为空");
      return;
    }
    if (!editFormData.oid.toString().trim()) {
      ElMessage.warning("机构ID不能为空");
      return;
    }
    if (!editFormData.class_name.trim()) {
      ElMessage.warning("类型名称不能为空");
      return;
    }

    const response = await updateInstitution(editFormData);
    if (response.status === "success") {
      ElMessage.success("修改成功");
      editDialogVisible.value = false;
      // 重新加载数据
      await loadInstitutionData();
    } else {
      ElMessage.error("修改失败");
    }
  } catch (error) {
    console.error("修改机构失败:", error);
    ElMessage.error("修改失败");
  }
};

// 根据class_id获取对应的class_name
const getClassNameByClassId = (classId: number): string => {
  switch (classId) {
    case 1:
      return "学校";
    case 2:
      return "机构";
    case 3:
      return "企业";
    case 4:
      return "科室";
    case 5:
      return "学部";
    case 6:
      return "部门";
    default:
      return "未知";
  }
};

onMounted(() => {
  loadInstitutionData();
});
</script>

<template>
  <div class="institution-container">
    <el-card class="institution-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">河南农业大学组织机构管理</span>
        </div>
      </template>
      <el-tree
        :data="tableData"
        :props="{
          children: 'children',
          label: 'zh_name'
        }"
        node-key="id"
        :default-expanded-keys="expandRowKeys"
        :expand-on-click-node="false"
      >
        <template #default="{ data }">
          <div class="custom-tree-node">
            <div class="node-content">
              <span class="node-id">{{ data.oid }}</span>
              <span class="node-name">{{ data.zh_name }}</span>
              <span
                class="node-type"
                :class="{
                  'type-school': data.class_id === 1,
                  'type-org': data.class_id === 2,
                  'type-enterprise': data.class_id === 3,
                  'type-office': data.class_id === 4,
                  'type-division': data.class_id === 5,
                  'type-dept': data.class_id === 6
                }"
              >
                {{ data.class_name }}
              </span>
            </div>
            <div class="operation-group">
              <el-tag
                type="primary"
                class="operation-tag"
                effect="light"
                @click="handleEdit(data)"
              >
                修改
              </el-tag>
              <el-tag
                type="danger"
                class="operation-tag"
                effect="light"
                @click="handleDelete(data)"
              >
                删除
              </el-tag>
              <el-tag
                type="success"
                class="operation-tag"
                effect="light"
                @click="handleAddChild(data)"
              >
                新增下一级
              </el-tag>
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>

    <!-- 新增下一级弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增下一级"
      width="500px"
      destroy-on-close
    >
      <el-form :model="formData" label-width="100px" class="institution-form">
        <el-form-item label="机构ID" required>
          <el-input v-model="formData.oid" placeholder="请输入机构ID" />
        </el-form-item>
        <el-form-item label="父级ID" required>
          <el-input
            v-model="formData.pid"
            placeholder="请输入父级ID"
            disabled
          />
        </el-form-item>
        <el-form-item label="机构名称" required>
          <el-input v-model="formData.zh_name" placeholder="请输入机构名称" />
        </el-form-item>
        <el-form-item label="类型" required>
          <el-select v-model="formData.class_id" @change="handleTypeChange">
            <el-option
              v-for="type in availableChildTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型名称" required>
          <el-input v-model="formData.class_name" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改机构弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改机构"
      width="500px"
      destroy-on-close
    >
      <el-form
        :model="editFormData"
        label-width="100px"
        class="institution-form"
      >
        <el-form-item label="ID" required>
          <el-input v-model="editFormData.id" type="number" disabled />
        </el-form-item>
        <el-form-item label="机构ID" required>
          <el-input v-model="editFormData.oid" placeholder="请输入机构ID" />
        </el-form-item>
        <el-form-item label="机构名称" required>
          <el-input
            v-model="editFormData.zh_name"
            placeholder="请输入机构名称"
          />
        </el-form-item>
        <el-form-item label="父级ID" required>
          <el-input v-model="editFormData.pid" placeholder="请输入父级ID" />
        </el-form-item>
        <el-form-item label="类型ID" required>
          <el-input
            v-model="editFormData.class_id"
            type="number"
            placeholder="请输入类型ID"
          />
        </el-form-item>
        <el-form-item label="类型名称" required>
          <el-input
            v-model="editFormData.class_name"
            placeholder="请输入类型名称"
          />
        </el-form-item>
        <el-form-item label="序号ID">
          <el-input
            v-model="editFormData.seqnum_id"
            type="number"
            placeholder="请输入序号ID"
          />
        </el-form-item>
        <el-form-item label="是否有效" required>
          <el-select
            v-model="editFormData.is_valid"
            placeholder="请选择是否有效"
          >
            <el-option :value="1" label="是" />
            <el-option :value="0" label="否" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.institution-container {
  height: 100%;
  padding: 20px;
}

.institution-card {
  margin-bottom: 20px;

  :deep(.el-card__header) {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
  }
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .header-title {
    font-size: 18px;
    font-weight: bold;
  }
}

.field-description {
  padding: 15px;
  margin-bottom: 20px;
  background-color: #fafafa;
  border-radius: 4px;

  .field-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .field-label {
    width: 100px;
    font-weight: bold;
    color: #606266;
  }

  .field-example {
    font-family: monospace;
    color: #909399;
  }

  .type-examples {
    display: flex;
    gap: 10px;
    align-items: center;

    .node-type {
      padding: 2px 6px;
      font-size: 12px;
      border-radius: 4px;
    }
  }
}

.institution-table {
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.operation-tag {
  padding: 4px 8px;
  margin: 0 4px;
  font-size: 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;

  &:hover {
    opacity: 0.8;
    transform: translateY(-2px);
  }

  &:active {
    transform: translateY(0);
  }
}

.id-tag {
  font-family: monospace;
  letter-spacing: 0.5px;
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.05);
  }
}

.institution-form {
  padding: 20px;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  :deep(.el-form-item.is-required .el-form-item__label::before) {
    color: var(--el-color-danger);
  }
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

:deep(.custom-tree-node) {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;

  .node-content {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .node-id {
    font-family: monospace;
  }

  .node-type {
    padding: 2px 6px;
    font-size: 12px;
    border-radius: 4px;

    &.type-school {
      color: #1890ff;
      background-color: #e6f7ff;
    }

    &.type-org {
      color: #52c41a;
      background-color: #f6ffed;
    }

    &.type-enterprise {
      color: #eb2f96;
      background-color: #fff0f6;
    }

    &.type-office {
      color: #595959;
      background-color: #f5f5f5;
    }

    &.type-division {
      color: #722ed1;
      background-color: #f9f0ff;
    }

    &.type-dept {
      color: #fa8c16;
      background-color: #fff7e6;
    }
  }

  .operation-group {
    display: flex;
    gap: 8px;
  }
}

:deep(.el-tree-node) {
  .el-tree-node__content {
    height: 40px;
  }
}

:deep(.el-select) {
  width: 100%;
}
</style>
